import si from "systeminformation";
import contrib from "blessed-contrib";

const colors = ["magenta", "cyan", "blue", "yellow", "green", "red"];

type CpuData = {
  title: string;
  style: {
    line: string;
  };
  x: number[];
  y: number[];
};

class CpuMonitor {
  lineChart: contrib.Widgets.PictureElement;
  cpuData: CpuData[] = [];
  interval: NodeJS.Timeout | null = null;

  constructor(line: contrib.Widgets.PictureElement) {
    this.lineChart = line;
  }

  init() {
    si.currentLoad((data) => {
        // init 里刚开始在不同位置填充 60 个 0，渲染一次。
      this.cpuData = data.cpus.map((cpu, i) => {
        return {
          title: "CPU" + (i + 1),
          style: {
            line: colors[i % colors.length],
          },
          x: Array(60)
            .fill(0)
            .map((_, i) => 60 - i),
          y: Array(60).fill(0),
        };
      });
      this.updateData(data);
    //   之后每一秒获取 cpu 数据，重新渲染。
      this.interval = setInterval(() => {
        si.currentLoad((data) => {
          this.updateData(data);
        });
      }, 1000);
    });
  }

  updateData(data: si.Systeminformation.CurrentLoadData) {
    data.cpus.forEach((cpu, i) => {
      let loadString = cpu.load.toFixed(1).toString();
      while (loadString.length < 6) {
        loadString = " " + loadString;
      }
      loadString = loadString + "%";
      this.cpuData[i].title = "CPU" + (i + 1) + loadString;
    //   如何实现这种不断左移的效果呢？也就是数组里 shift 删除了一个前面的元素，然后 push 添加了一个后面的元素。
      this.cpuData[i].y.shift();
      this.cpuData[i].y.push(cpu.load);
    });
    this.lineChart.setData(this.cpuData);
    this.lineChart.screen.render();
  }
}

export default CpuMonitor;